import json
import time

import tornado
import tornado.websocket
import tornado.web
from db import db
from util.myredis import r
conndict = {}

class WebsockHandler(tornado.websocket.WebSocketHandler):
    # 跨域支持
    def check_origin(self,origin):
        return True
    #建立连接
    def open(self):
        # 获取参数
        id = int(self.get_query_argument('id'))
        # 存储链接
        conndict[id] = self

    def on_message(self,mes):
        print(mes)
    def on_close(self):
        pass

class TTHander(tornado.web.RequestHandler):
    def get(self):
        msg = self.get_query_argument('mes')
        id = int(self.get_query_argument('id'))
        conndict[id].write_message(msg)



class Greenhouse(tornado.web.RequestHandler):
    def get(self):
        id = int(self.get_query_argument('id'))
        while True:

            web = r.str_get('key')
            print(web)
            if web:
                key = int(web.decode())
                sql = "select * from greenhouse"
                res = db.findall(sql)
                print(res)
                list = []
                for i in res:
                    if i['min'] <=key<=i['max']:
                        status = 1
                        list.append({'id':i['id'],'name':i['name'],'min':i['min'],'max':i['max'],'status':status,'key':key})
                    else:
                        status = 0
                        list.append({'id':i['id'],'name':i['name'],'min':i['min'],'max':i['max'],'status':status,'key':key})
                time.sleep(3)
                conndict[id].write_message(json.dumps(list))



# def send():
#     key1 = 'key1'
#     a= key1[-1]
#     print(a)
# send()
